<template>
  <view class="w-full max-w-[750rpx] mx-auto min-h-screen bg-[#f6f8fa] p-[32rpx] box-border">
    <text class="block text-[48rpx] font-extrabold mb-[40rpx] text-center text-blue-600 drop-shadow">编辑既往病史</text>
    <FormView :fieldConfig="fieldConfig" :form="form" :showButtons="true" @submit="submitForm" />
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import { pastMedicalFields as fieldConfig } from './fields'
import FormView from '@/components/FormView.vue'
import { request } from '@/service/request'

const form = reactive<any>({})
const recordId = ref<string>('')

onMounted(async () => {
  // 获取路由参数
  const params = Taro.getCurrentInstance().router?.params
  if (params?.id) {
    recordId.value = params.id
    await loadRecordData(params.id)
  }
})

async function loadRecordData(id: string) {
  try {
    const result = await request.get<any>(`/health_records/past_medical/pastMedicalInfo/detail/${id}`, {}, {
      useErrMsg: true
    })
    
    if (result) {
      // 将数字值转换为显示文本
      const displayData = {
        ...result,
        ifDisease: result.ifDisease === 1 ? '是' : '否',
        ifFamDis: result.ifFamDis === 1 ? '是' : '否',
        ifGeneticDis: result.ifGeneticDis === 1 ? '是' : '否',
        ifOpera: result.ifOpera === 1 ? '是' : '否',
        ifTrauma: result.ifTrauma === 1 ? '是' : '否',
        ifInbloob: result.ifInbloob === 1 ? '是' : '否',
        allergy: result.allergy === 1 ? '有' : '无',
        expose: result.expose === 1 ? '有' : '无'
      }
      Object.assign(form, displayData)
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    Taro.showToast({ title: '加载数据失败', icon: 'error' })
  }
}

async function submitForm(form: any, fieldConfig: any) {
  try {
    // 表单验证
    if (!form.name) {
      Taro.showToast({ title: '请输入姓名', icon: 'error' })
      return
    }
    if (!form.idNumber) {
      Taro.showToast({ title: '请输入证件号码', icon: 'error' })
      return
    }

    // 提交数据
    const params = {
      ...form,
      id: recordId.value,
      // 将选择器值转换为数字
      ifDisease: form.ifDisease === '是' ? 1 : 0,
      ifFamDis: form.ifFamDis === '是' ? 1 : 0,
      ifGeneticDis: form.ifGeneticDis === '是' ? 1 : 0,
      ifOpera: form.ifOpera === '是' ? 1 : 0,
      ifTrauma: form.ifTrauma === '是' ? 1 : 0,
      ifInbloob: form.ifInbloob === '是' ? 1 : 0,
      allergy: form.allergy === '有' ? 1 : 0,
      expose: form.expose === '有' ? 1 : 0,
      recordid: form.recordid ? parseInt(form.recordid) : 0
    }
    
    const result = await request.put<any>(`/health_records/past_medical/pastMedicalInfo/update`, params, {
      useErrMsg: true
    })
    
    if (result) {
      Taro.showToast({ title: '更新成功', icon: 'success' })
      // 返回上一页
      setTimeout(() => {
        Taro.navigateBack()
      }, 1500)
    }
  } catch (error) {
    console.error('更新失败:', error)
    Taro.showToast({ title: '更新失败', icon: 'error' })
  }
}
</script>